layui.define(['jdhp'], function (exports) {
    function design_in_main(args) {
        if (window.jdiyAdmin === undefined) window.jdiyAdmin = {};
        let body = $('body'),
            $g = s => $('#' + s + '_' + args.uid),
            canvas = $g('inCanvas'),
            rtForm = $g('inProps'),
            nolay = $g('noLayoutDiv'),
            optTypes = [
                [
                    ['table', '数据库表'],
                    ['entity', 'JPA实体'],
                    ['dict', '数据字典'],
                    ['sql', 'SQL查询'],
                    ['jql', 'JQL查询']
                ],
                [
                    ['table', '数据库表'],
                    ['entity', 'JPA实体']
                ]
            ],
            $gs = function (s, h = []) {
                if (s.length) for (let i = s.length; i--;) $g(s[i]).show();
                if (h.length) for (let i = h.length; i--;) $g(h[i]).hide();
            },
            $selected = () => ({t: canvas.find('.jdiy-selected'), d: eData[canvas.find('.jdiy-selected').attr('id')]}),
            fillOpts = (o, pleaseText, items, selVal, jgFunc = (it) => it) => {
                let sa = pleaseText === false ? [] : ['<option value="">' + pleaseText + '</option>'];
                for (let i = 0; i < items.length; i++) {
                    let [v, k] = jgFunc(items[i]);
                    sa.push('<option value="' + v + '"' + (String(v) === String(selVal) ? ' selected' : '') + '>' + k + '</option>');
                }
                return o.html(sa.join(''));
            },
            selectOn = function (a, b) {
                layui.form.on('select(' + a + '_' + args.uid + ')', b);
            },
            switchOn = function (a, b) {
                layui.form.on('switch(' + a + '_' + args.uid + ')', b);
            },
            sData = {},
            eData = [],
            addNewId = 1,
            inputval = function (d) {
                let r = d.field || '';
                if (d.format === 'joinTable') {
                    r += ' (' + d.joinTable + '.' + (d.joinField || '') + ')';
                } else if (d.format === 'joinEntity') {
                    let x = d.joinEntity || '';
                    x = x.substring(x.lastIndexOf(".") + 1);
                    r += ' (' + x + '.' + (d.joinField || '') + ')';
                } else if (d.format === 'pwd') {
                    if (d.pwdType && d.pwdType !== '') r += ' (' + d.pwdType + ')';
                }
                return r;
            },
            startDrag = function (e, dragThis) {
                body.addClass('drag-move');
                jdiyAdmin.inDesign.dragging = true;
                jdiyAdmin.inDesign.dragThis = dragThis.css({opacity: 0.1});
                jdiyAdmin.inDesign.mouse = {x: e.clientX, y: e.clientY};
            },
            doSelect = function (target) {
                if (typeof target == 'string') target = $('#' + target);
                if (target.length) {
                    if (!$g('rtTab0').hasClass('layui-this')) layui.element.tabChange('rtTab_' + args.uid, 'rtTab0_' + args.uid);
                    canvas.find('.jdiy-selected').removeClass('jdiy-selected');
                    target.addClass('jdiy-selected');
                    canvas.find('.jdiy-in-thisRow').removeClass('jdiy-in-thisRow');
                    target.parents('.layui-form-item').addClass('jdiy-in-thisRow');
                    $gs([], ['nulPropDiv']);
                    let d = eData[target.attr('id')];
                    setTimeout(function () {
                        builder.showProp(d.type, d);
                    }, 100);/*一定要加个定时器防止上一个控件属性还没有来得及保存*/
                } else {
                    builder.showProp();
                }
                showTool();
            },
            reset = function (data, selectedId) {
                let _done = function () {
                    sData = data;
                    let sa = [], lastRow = -1;

                    if (sData.inputs && sData.inputs.length) {
                        for (let i = 0; i < sData.inputs.length; i++) {
                            let d = sData.inputs[i];
                            if (lastRow === -1 || lastRow !== d.row) {
                                if (lastRow !== -1) sa.push('</div>')
                                sa.push('<div class="layui-form-item">');
                                lastRow = d.row;
                            }
                            eData[d.id] = d;
                            sa.push(builder.wrap(d));
                            if (i === sData.inputs.length - 1) sa.push('</div>');
                        }
                    }
                    if (sa.length) {
                        canvas.html(sa.join('\n'));
                        if (selectedId) doSelect(selectedId);
                        else builder.showProp();
                    } else {
                        builder.empty();
                    }
                    _escssFn(data.eventScript);
                    if (data.pkTpl !== 'pres') $gs([], ['pkPreDiv']);
                    if (data.pkTpl !== 'pres' && data.pkTpl !== 'dates') $gs([], ['pkLenDiv']);

                    $g('ajaxSave').prop('checked', !!data.ajaxSave);
                    $g('ajaxUrl').val(data.ajaxUrl);
                    if (data.ajaxSave) {
                        $gs(['ajaxUrlDiv']);
                    } else {
                        $gs([], ['ajaxUrlDiv']);
                    }

                    $g('pkTpl').val(data.pkTpl);
                    $g('pkPre').val(data.pkPre);
                    $g('pkLen').val(data.pkLen);
                    $g('hiddenParams').val(data.hiddenParams);
                    $g('pageHandler').val(data.pageHandler);

                    $g('headTips').val(data.headTips || '');
                    if (data.headTips != null && data.headTips !== '') {
                        $g('headTipsBlock').html(data.headTips).show();
                    }
                    $g('footTips').val(data.footTips || '');
                    if (data.footTips != null && data.footTips !== '') {
                        $g('footTipsBlock').html(data.footTips).show();
                    }

                    layui.form.render(null, canvas.attr('id'));
                    layui.form.render(null, rtForm.attr('id'));
                };
                if (data) {
                    _done();
                } else {
                    jdiyAdmin.ajax({
                        url: jdiyAdmin.ctx + '/mgmt/JDiyAdmin/ui.meta?pageId=' + args.uid,
                        type: 'post',
                        success: function (ret) {
                            if (ret.code !== 200) {
                                jdiyAdmin.error(ret.msg);
                                return;
                            }
                            reset(ret.data, selectedId);
                        }
                    });
                }
            },
            save = function () {
                let r, e, ri = 0, ci, selectedId = canvas.find('.jdiy-selected').attr('id'), inputs = [];
                canvas.find('.layui-form-item').each(function () {
                    r = $(this).find('.jdiy-in-obj');
                    if (r.length > 0) {
                        ci = 0;
                        r.each(function () {
                            e = eData[$(this).attr('id')];
                            e.row = ri;
                            e.col = ci++;
                            inputs.push(e);
                        });
                        ri++;
                    }
                });
                if (inputs.length === 0) {
                    jdiyAdmin.error('您还没有添加配置任何表单控件！');
                    return;
                }

                jdiyAdmin.ajax({
                    url: jdiyAdmin.ctx + '/mgmt/JDiyAdmin/form.saveDesign.' + args.uid,
                    data: {
                        s: JSON.stringify({
                            pkTpl: $g('pkTpl').val() || null,
                            pkLen: $g('pkLen').val(),
                            pkPre: $g('pkPre').val(),
                            ajaxSave: !!sData.ajaxSave,
                            ajaxUrl: sData.ajaxUrl,
                            pageHandler: $g('pageHandler').val(),
                            headTips: sData.headTips || '',
                            footTips: sData.footTips || '',
                            hiddenParams: $g('hiddenParams').val(),
                            eventScript: sData.eventScript || '',
                            inputs: inputs
                        })
                    },
                    type: 'post',
                    success: function (ret) {
                        if (ret.code !== 200) {
                            if (ret.code === 203 && ret.inputId) doSelect(ret.inputId);
                            jdiyAdmin.error(ret.msg);
                            return;
                        }
                        reset(null, selectedId);
                        layui.layer.msg(ret.msg);
                    }
                });
            },
            addNew = function (first) {
                let nid = jdiyAdmin.util.newId(),
                    nd = {
                        id: nid,
                        type: 'input',
                        label: '新控件' + addNewId++,
                        format: 'text',
                        layout: 'inline'
                    }, ok = false,
                    n = $('<div class="layui-form-item">' + builder.wrap(eData[nid] = nd) + '</div>');
                if (first) {
                    n = n.appendTo(canvas).children(':first');
                    ok = true;
                } else {
                    let t = canvas.find('.jdiy-selected').parents('.layui-form-item');
                    if (t.length) {
                        n = n.insertAfter(t).children(':first');
                        ok = true;
                    }
                }
                if (ok) {
                    doSelect(n);
                    layui.layer.msg('[' + nd.label + '] 已添加并选中，请在页面右侧配置其属性。');
                }
            },
            toolHtml = '<div class="layui-btn-group jdiy-design-tool">\n' +
                '        <button type="button" class="layui-btn layui-btn-xs layui-bg-black add-tool" title="在下方添加一个新控件"><i class="layui-icon layui-icon-add-1"></i></button>\n' +
                '        <button type="button" class="layui-btn layui-btn-xs layui-bg-black del-tool" title="移除此控件"><i class="layui-icon layui-icon-delete"></i></button>\n' +
                '    </div>',
            showTool = function (h) {
                canvas.find('.jdiy-design-tool').remove();
                if (h === true) return;
                let {t, d} = $selected();
                if (t.length) {
                    let tool = d.layout.indexOf('col') === 0 || d.type === 'file'
                        ? $(toolHtml).prependTo(t).css({
                            marginLeft: 0,
                            marginTop: (t.outerHeight()) + 'px'
                        })
                        : $(toolHtml).insertBefore(t).css({
                            marginLeft: '110px',
                            marginTop: (t.outerHeight()) + 'px'
                        });
                    tool.find('.add-tool').click(function () {
                        addNew();
                    });
                    tool.find('.del-tool').click(function () {
                        let t = canvas.find('.jdiy-selected'),
                            i = t.attr('id'),
                            l = eData[i].label,
                            p = t.parent(), n;
                        t.remove();
                        p.find('.jdiy-design-tool').remove();
                        if (p.children().length < 1) {
                            n = p.next().find('.jdiy-in-obj:first');
                            p.remove();
                        } else {
                            n = p.find('.jdiy-in-obj:first');
                        }
                        if (n.length !== 1) n = canvas.find('.jdiy-in-obj:last');
                        if (n.length === 1) doSelect(n);
                        else builder.empty();
                        delete eData[i];
                        layui.layer.msg('[' + l + '] 已从当前设计区移除！');
                    });
                }
            },
            loadFields = function (e, et, s) {
                !et ? s({code: 200, data: []}) :
                    $.ajax({
                        url: jdiyAdmin.ctx + '/mgmt/JDiyAdmin/ui.' + (e ? 'fields?entity=' : 'columns?table=') + et,
                        success: s
                    });
            },
            joinTableOn = function (o) {
                let {t, d} = $selected();
                if (d.format === 'joinEntity')
                    d.joinEntity = o.value;
                else
                    d.joinTable = o.value;
                loadFields(d.format === 'joinEntity', o.value, function (r) {
                    d.joinField = fillOpts($g('joinField'), '查询字段', r.data, d.joinField, (it) => [
                        it[0], it[0] + '　- ' + it[1]
                    ]).val();
                    layui.form.render('select', rtForm.attr('id'));
                    t.find('input').val(inputval(d));
                });
            },
            lookupJoinTableOn = function (o) {
                let {d} = $selected();
                d.lookupJoinTable = o.value;
                loadFields(false, o.value, function (r) {
                    let jg = (it) => [it[0], it[0] + '　- ' + it[1]];
                    d.lookupJoinField0 = fillOpts($g('lookupJoinField0'), '正向关联本表字段', r.data, d.lookupJoinField0, jg).val();
                    d.lookupJoinField1 = fillOpts($g('lookupJoinField1'), '反向关联外表字段', r.data, d.lookupJoinField1, jg).val();
                    layui.form.render('select', rtForm.attr('id'));
                });
            },
            lookupTypeOn = function (o) {
                let {d} = $selected();
                switch (d.lookupType = o.value) {
                    case 'OneToMany':
                        $gs(['lookupJoinFieldDiv'], ['lookupJoinTableDiv', 'lookupJoinField0Div', 'lookupJoinField1Div']);
                        $g('lookupJoinField').val(d.lookupJoinField);
                        break;
                    case 'ManyToMany':
                        $gs(['lookupJoinTableDiv', 'lookupJoinField0Div', 'lookupJoinField1Div'], ['lookupJoinFieldDiv']);
                        $g('lookupJoinTable').val(d.lookupJoinTable || '');
                        lookupJoinTableOn({value: d.lookupJoinTable});
                        break;
                    default:
                        $gs([], ['lookupJoinFieldDiv', 'lookupJoinTableDiv', 'lookupJoinField0Div', 'lookupJoinField1Div']);
                }
                layui.form.render('select', rtForm.attr('id'));
            },
            lookupMutiOn = function (o) {
                let {d} = $selected();
                if (!!(d.lookupMulti = o.elem.checked)) {
                    $gs(['lookupTypeDiv']);
                    $g('lookupTypeOn').val(d.lookupType = d.lookupType || 'none');
                    lookupTypeOn({value: d.lookupType});
                } else {
                    $gs([], ['lookupTypeDiv', 'lookupJoinFieldDiv', 'lookupJoinTableDiv', 'lookupJoinField0Div', 'lookupJoinField1Div']);
                }
                layui.form.render('select', rtForm.attr('id'));
            },
            lookupIdOn = function (o) {
                let {d} = $selected();
                if (!(d.lookupId = o.value)) {
                    d.lookupField = fillOpts($g('lookupField'), '', []).val();
                    d.lookupJoinField = fillOpts($g('lookupJoinField'), '', []).val();
                    layui.form.render('select', rtForm.attr('id'));
                    return;
                }
                $.each(args.pageList, function (i, u) {
                    if (u.id === d.lookupId) {
                        loadFields(false, u.mainTable, function (r) {
                            d.lookupField = fillOpts($g('lookupField'), '查找带回显示字段', r.data, d.lookupField, (it) => [
                                it[0], it[0] + '　- ' + it[1]
                            ]).val();
                            d.lookupJoinField = fillOpts($g('lookupJoinField'), '请选择外键', r.data, d.lookupJoinField, (it) => [
                                it[0], it[0] + '　- ' + it[1]
                            ]).val();
                            layui.form.render('select', rtForm.attr('id'));
                        });
                        return false;
                    }
                });
            },

            manyTableOn = function (o) {
                let {d} = $selected();
                d.manyTable = o.value;
                loadFields(false, o.value, function (r) {
                    let jg = (it) => [it[0], it[0] + '　- ' + it[1]];
                    d.manyField0 = fillOpts($g('manyField0'), '正向关联本表字段', r.data, d.manyField0, jg).val();
                    d.manyField1 = fillOpts($g('manyField1'), '反向关联外表字段', r.data, d.manyField1, jg).val();
                    layui.form.render('select', rtForm.attr('id'));
                });
            },
            optTableOn = function (o) {
                let {d} = $selected(),
                    ok = function (data) {
                        let jg = (it) => [it[0], it[0] + '　- ' + it[1]];
                        fillOpts($g('optTxtField'), '请选择', data, d.optTxtField, jg);
                        fillOpts($g('optValField'), '请选择', data, d.optValField, jg);
                        layui.form.render('select', rtForm.attr('id'));
                    };

                if (!o.value) {
                    ok([]);
                    return;
                }
                loadFields(d.optType === 'entity', o.value, function (r) {
                    if (r.code === 200 && r.data) {
                        ok(r.data);
                    } else ok([]);
                });
            },
            optTypeOn = function (o) {
                let {d} = $selected();
                d.optType = o.value || null;
                if (o.value === 'entity') {
                    $gs(['optsTEDiv', 'optEntityDiv', 'cascadeDiv'], ['optTableDiv', 'optDictDiv', 'optQryDiv']);
                    optTableOn({value: $g('optEntity').val(d.optEntity || '').val()});
                    $g('optWhere').val(d.optWhere);
                    $g('optSort').val(d.optSort);
                    $g('optWhere').attr('placeholder', "(JPQL条件片段)\n例：o.parent.id=3 and o.user.id='${user.id}'");
                } else if (o.value === 'table') {
                    $gs(['optsTEDiv', 'optTableDiv', 'cascadeDiv'], ['optEntityDiv', 'optDictDiv', 'optQryDiv']);
                    optTableOn({value: $g('optTable').val(d.optTable || '').val()});
                    $g('optWhere').val(d.optWhere);
                    $g('optSort').val(d.optSort);
                    $g('optWhere').attr('placeholder', "(SQL条件片段)\n例：o.tid=3 and o.user_id='${user.id}'");
                } else if (o.value === 'dict') {
                    //todo 动态加载dict并设置初值
                    $g('optDict').val(d.optDict);
                    $gs(['optDictDiv'], ['optsTEDiv', 'optQryDiv', 'cascadeDiv']);
                } else if (o.value === 'jql') {
                    $gs(['optQryDiv', 'cascadeDiv'], ['optsTEDiv', 'optDictDiv']);
                    $g('optQry').val(d.optQry || '')
                        .attr('placeholder', '例：select o.id as id,o.name as name from Xxx o where o.parent.id=9 and user.id=\'${user.id}\'');
                } else if (o.value === 'sql') {
                    $gs(['optQryDiv', 'cascadeDiv'], ['optsTEDiv', 'optDictDiv']);
                    $g('optQry').val(d.optQry || '')
                        .attr('placeholder', '例：select id,name from xxx where tid=9 and user_id=\'${user.id}\'');
                } else {
                    $gs([], ['optsTEDiv', 'optEntityDiv', 'optTableDiv', 'optDictDiv', 'optQryDiv', 'cascadeDiv']);
                }
                $g('cascade').prop('checked', d.cascade);
            },
            builder = {
                empty: function () {
                    let aid = jdiyAdmin.util.newId();
                    canvas.html('<div style="padding:50px;text-align: center;border:1px #c00 dotted;">\n' +
                        '<div style="margin-bottom: 20px;font-size:16px;color:red;">空空如也，请点击下面按钮添加控件。</div>\n' +
                        '<button type="button" id="' + aid + '" class="layui-btn layui-btn-sm addFirst layui-btn-danger"><i class="layui-icon layui-icon-add-1"></i>添加控件</button>\n' +
                        '</div>');
                    $('#' + aid).click(function () {
                        canvas.html('');
                        addNew(true);
                    });

                    builder.showProp();
                },
                row: function (canvas, rowArray) {
                    let sa = [], i, d;
                    for (i = 0; i < rowArray.length; i++) {
                        d = rowArray[i];
                        eData[d.id] = d;
                        sa.push(builder.wrap(d));
                    }
                    return sa.join('\n');
                },
                wrap: function (d) {
                    let layCss, labelCss = 'layui-form-label', sa = [];
                    if (d.type === 'ueditor' || d.type === 'file') layCss = 'noInline';
                    else if (d.layout === 'col12') layCss = 'layui-col-xs12';
                    else if (d.layout === 'col6') layCss = 'layui-col-xs6';
                    else if (d.layout === 'col4') layCss = 'layui-col-xs4';
                    else if (d.layout === 'col3') layCss = 'layui-col-xs3';
                    else layCss = 'layui-inline';
                    if (d.layout === 'free') labelCss = 'free';
                    if (d.readonly - 0) layCss += ' readonly';

                    sa.push('<div class="' + layCss + ' jdiy-in-obj" id="' + d.id + '">');
                    if (d.type !== 'textarea' && d.type !== 'ueditor' && d.type !== 'file') {
                        sa.push('<label class="' + labelCss + '">' + d.label + '</label>');
                    }
                    if (builder.item[d.type]) sa.push(builder.item[d.type].call(d));
                    else sa.push('<span style="color:red">未知控件类型' + d.type + '</span>');
                    if(d.layout=='inline' && d.type!='file' && d.type!='ueditor') sa.push('<div class="layui-form-mid" id="'+d.id+'__tips" style="color:grey;">'+(d.tips||'')+'</div>');
                    else if(d.layout=='free' && d.type!='file' && d.type!='ueditor')sa.push('<span id="'+d.id+'__tips" style="color:grey;">'+(d.tips||'')+'</span>');
                    sa.push('</div>');
                    return sa.join('\n');
                },
                item: {
                    input: function () {
                        let val = inputval(this),
                            inpW = this.layout === 'free' && this.width > 0 ? ' style="width:' + this.width + 'px"' : '',
                            cls = this.layout === 'free' ? 'layui-inline' : (this.layout.indexOf('col') === 0 ? 'layui-input-block' : 'layui-input-inline');
                        return '<div class="' + cls + ' inpDiv"' + inpW + '>' + '<input type="text" readonly placeholder="' + (this.placeholder || '') + '" value="' + val + '" class="layui-input layui-unselect"/></div>';
                    },
                    colorbox: function () {
                        let val = inputval(this);
                        inpW = this.layout === 'free' && this.width > 0 ? ' style="width:' + this.width + 'px"' : '',
                            cls = this.layout === 'free' ? 'layui-inline' : (this.layout.indexOf('col') === 0 ? 'layui-input-block' : 'layui-input-inline');
                        // return '<div class="' + cls + ' inpDiv"' + inpW + '>' + '<input type="text" readonly placeholder="' + (this.placeholder || '') + '" value="' + val + '" class="layui-input layui-unselect"/></div>';
                        return '<div class="' + cls + ' inpDiv"' + inpW + '><div class="layui-input-inline" style="width: 100%;">' +
                            '<div style="position: absolute;right:0;margin-right: 0;" class="layui-inline"><div class="layui-unselect layui-colorpicker"><span><span class="layui-colorpicker-trigger-span" lay-type="" style="background: ' +
                            (this.initial || '##01aaed') +
                            ' none repeat scroll 0% 0%;"><i class="layui-icon layui-colorpicker-trigger-i layui-icon-down"></i></span></span></div></div>' +
                            '<input type="text" value="' + val + '" placeholder="" class="layui-input layui-form-danger">' +
                            '</div></div>';
                    },
                    lookup: function () {
                        let val = inputval(this),
                            inpW = this.layout === 'free' && this.width > 0 ? ' style="width:' + this.width + 'px"' : '',
                            cls = this.layout === 'free' ? 'layui-inline' : (this.layout.indexOf('col') === 0 ? 'layui-input-block' : 'layui-input-inline');

                        return '<div class="' + cls + ' inpDiv"' + inpW + '>' +
                            '<div class="jdiy-lookup"><div class="jdiy-lookup-item add"><i class="layui-icon layui-icon-search"></i>选择</div><div class="tips" style="margin-top:6px;">&nbsp;' + val + '</div></div>'
                            + '</div>';
                    },
                    textarea: function () {
                        let height = this.height || 100;
                        if (height < 60) height = 60;
                        let labelH = height - 18,
                            val = this.field || '',
                            inpW = this.layout === 'free' && this.width > 0 ? ' style="width:' + this.width + 'px"' : '',
                            labCss = this.layout === 'free' ? 'free' : 'layui-form-label',
                            cls = this.layout === 'free' ? 'layui-inline' : (this.layout.indexOf('col') === 0 ? 'layui-input-block' : 'layui-input-inline');
                        return '<label class="' + labCss + '" style="height:' + labelH + 'px;">' + this.label +
                            '</label><div class="' + cls + ' inpDiv"' + inpW + '><textarea type="text" placeholder="'
                            + (this.placeholder || '') + '" readonly class="layui-textarea layui-unselect" style="resize:none;height:' + height +
                            'px;">' + val + '</textarea></div>';
                    },
                    switcher: function () {
                        let val = inputval(this),
                            ont = this.ont === undefined || this.ont.indexOf('|') === -1 ? '开|关' : this.ont,
                            inpW = this.layout === 'free' && this.width > 0 ? ' style="width:' + this.width + 'px"' : '',
                            cls = this.layout === 'free' ? 'layui-inline' : (this.layout.indexOf('col') === 0 ? 'layui-input-block' : 'layui-input-inline');
                        return '<div class="' + cls + ' inpDiv"' + inpW + '>' +
                            '<input type="checkbox" name="' + this.id + '" checked="checked" lay-skin="switch" lay-text="' + ont + '"/><span class="tips" style="padding-top:12px;">　' + val + '</span></div>';
                    },
                    select: function () {
                        let val = this.field || '',
                            inpW = this.layout === 'free' && this.width > 0 ? ' style="width:' + this.width + 'px"' : '',
                            cls = this.layout === 'free' ? 'layui-inline' : (this.layout.indexOf('col') === 0 ? 'layui-input-block' : 'layui-input-inline');
                        return '<div class="' + cls + ' inpDiv"' + inpW + '><div class="layui-unselect layui-form-select">' +
                            '<div class="layui-select-title"><input type="text" placeholder="请选择" ' +
                            'value="' + val + (this.search ? '　带搜索' : '') + '" readonly="" class="layui-input layui-unselect"><i class="layui-edge"></i></div></div></div>';
                    },
                    treeSelect: function () {
                        let val = this.field || '',
                            inpW = this.layout === 'free' && this.width > 0 ? ' style="width:' + this.width + 'px"' : '',
                            cls = this.layout === 'free' ? 'layui-inline' : (this.layout.indexOf('col') === 0 ? 'layui-input-block' : 'layui-input-inline');
                        return '<div class="' + cls + ' inpDiv"' + inpW + '><div class="layui-unselect layui-form-select">' +
                            '<div class="layui-select-title"><input type="text" placeholder="请选择" ' +
                            'value="' + val + '" readonly="" class="layui-input layui-unselect"><i class="layui-edge"></i></div></div></div>';
                    },
                    checkbox: function () {
                        //复选框需要layui-input-block样式 可以直接栅格化
                        let ss = (this.items || '').trim().replace(/\s*\n+\s*/g, '\n');
                        ss += '\n1:选项1\n2:选项2';
                        let sa = ss.split('\n'), sb = [], i, it,
                            inpW = this.layout === 'free' && this.width > 0 ? ' style="width:' + this.width + 'px"' : '',
                            cls = this.layout === 'free' ? 'layui-inline' : 'layui-input-block';
                        for (i = 0; i < sa.length; i++) {
                            if (sa[i].trim() === '' || sa[i].indexOf(":") === -1) continue;
                            it = sa[i].split(':');
                            sb.push('<input type="checkbox" name="' + this.id + '" lay-skin="primary" title="' + it[1] + '" ' + (i === 0 ? ' checked=""' : '') + '/>');
                        }
                        if (sb.length > 2) sb.splice(-2, 2);
                        return '<div class="' + cls + ' inpDiv"' + inpW + '>' + sb.join('') + '<span class="tips">' + inputval(this) + '</span>' +
                            '<span id="'+this.id+'__tips" style="color:grey;">'+(this.tips||'')+'</span>' +
                            '</div>';
                    },
                    radio: function () {
                        //复选框需要layui-input-block样式 可以直接栅格化
                        let ss = (this.items || '').trim().replace(/\s*\n+\s*/g, '\n');
                        ss += '\n1:选项1\n2:选项2';
                        let sa = ss.split('\n'), sb = [], i, it,
                            cls = this.layout === 'free' ? 'layui-inline' : 'layui-input-block';
                        for (i = 0; i < sa.length; i++) {
                            if (sa[i].trim() === '' || sa[i].indexOf(":") === -1) continue;
                            it = sa[i].split(':');
                            sb.push('<input type="radio" name="' + this.id + '" title="' + it[1] + '" ' + (i === 0 ? ' checked=""' : '') + '/>');
                        }
                        if (sb.length > 2) sb.splice(-2, 2);
                        return '<div class="' + cls + ' inpDiv">' + sb.join('') + '<span class="tips">' + inputval(this) + '</span>' +
                            '<span id="'+this.id+'__tips" style="color:grey;">'+(this.tips||'')+'</span>' +
                            '</div>';
                    },
                    ueditor: function () {
                        let val = this.field || '';
                        return '<label class="layui-form-label" style="height:300px;">' + this.label +
                            '</label><div class="layui-input-block"><div class="layui-textarea layui-unselect" style="height:300px;width:100%;background: url(' +
                            jdiyAdmin.ctx + '/jdiy-admin-resource/img/editor_bg.png) 0 0 no-repeat;border:1px #ccc solid;border-radius: 5px;"><div style="margin:100px;" class="tips">' + val + '</div></div>' +
                            '<div id="'+this.id+'__tips" style="color:grey;">'+(this.tips||'')+'</div>' +
                            '</div>';
                    },
                    file: function () {
                        let val = inputval(this);
                        return '<label class="layui-form-label">' + this.label +
                            '</label><div class="layui-input-block"><input type="file" class="fileinput layui-unselect" style="margin-top:4px;"/><span class="tips">&nbsp;' + val + '</span>' +
                            '<span id="'+this.id+'__tips" style="color:grey;">'+(this.tips||'')+'</span>' +
                            '</div>';
                    }
                },
                showProp: function (type, d) {
                    $('#in_propAllDiv_' + args.uid + '>.layui-form-item').hide();
                    if (!type) {
                        $gs(['nulPropDiv'], ['layoutDiv']);
                        layui.element.tabChange('rtTab_' + args.uid, 'rtTab1_' + args.uid);
                        return;
                    }
                    let set = builder.propSet, so = function (some) {
                        let sa = some.split('|');
                        for (let i = sa.length; i--;) set[sa[i]](d[sa[i]], d);
                    };
                    set.type(type);
                    switch (type) {
                        case 'input':
                            if (d.format === 'joinTable') {
                                try {
                                    $g('joinTable').val(d.joinTable || '');
                                } catch (e) {
                                }
                                joinTableOn({value: d.joinTable});
                            } else if (d.format === 'joinEntity') {
                                try {
                                    $g('joinEntity').val(d.joinEntity || '');
                                } catch (e) {
                                }
                                joinTableOn({value: d.joinEntity});
                            } else if (d.format === 'pwd') {
                                try {
                                    $g('pwdType').val(d.pwdType || '');
                                } catch (e) {
                                }
                            }
                            so("field|label|format|required|readonly|maxlength|pattern|patternMsg|placeholder|tips|initial|layout|width|existsChk|conditionShow");
                            break;
                        case 'textarea':
                            so("field|label|required|readonly|maxlength|height|placeholder|tips|initial|pattern|patternMsg|layout|width|existsChk|conditionShow");
                            break;
                        case 'switcher':
                            so("field|label|readonly|initial|layout|width|ont|onv|conditionShow|tips");
                            break;
                        case 'select':
                            fillOpts($g('optType'), '不设置', optTypes[0], d.optType);
                            so("field|label|required|readonly|initial|layout|width|existsChk|search|opts|conditionShow|tips");
                            break;
                        case 'treeSelect':
                            so("field|label|treeId|required|readonly|maxlength|placeholder|tips|initial|layout|width|existsChk|conditionShow");
                            break;
                        case 'lookup':
                            set.lookup(d);
                            so("field|label|required|readonly|placeholder|tips|initial|layout|width|conditionShow");
                            break;
                        case 'checkbox':
                            let _mt = d.manyType = d.manyType || 'none';
                            set.manyType(_mt);
                            if (_mt === 'none') {
                                so("initial");
                                fillOpts($g('optType'), '不设置', optTypes[0], d.optType);
                            } else {
                                fillOpts($g('optType'), '请选择', optTypes[1], d.optType);
                            }
                            so("field|label|opts|readonly|minChk|maxChk|layout|width|conditionShow|tips");
                            break;
                        case 'radio':
                            so("field|label|readonly|opts|initial|layout|width|existsChk|conditionShow|tips");
                            fillOpts($g('optType'), '不设置', optTypes[0], d.optType);
                            break;
                        case 'ueditor':
                            set.label(d.label || '正文内容');
                            set.layout(null);
                            so("field|required|readonly|initial|width|conditionShow|tips");
                            break;
                        case 'colorbox':
                            set.label(d.label || '选择颜色');
                            so("field|required|readonly|initial|placeholder|tips|tips|layout|width|conditionShow");
                            break;
                        case 'file':
                            set.label(d.label || '文件上传');
                            set.fileType(d.fileType || (d.fileType = 'any'));
                            if (d.fileType === 'custom') set.fileExtensions(d.fileExtensions);
                            set.fileMultipart(d.fileMultipart || (d.fileMultipart = 'one'));
                            if (d.fileType === 'image') set.room(d.room || (d.room = 'none'));
                            if (d.fileType === 'image' && d.room !== 'none') {
                                set.roomTo(isNaN(d.roomW) ? d.roomW = 0 : d.roomW, isNaN(d.roomH) ? d.roomH = 0 : d.roomH);
                            }
                            set.layout(null);
                            so("field|fileDel|fileSize|renameType|fileName|required|noStore|readonly|width|conditionShow|tips");
                            break;
                    }
                    layui.form.render(null, rtForm.get('id'));
                },
                propSet: {
                    lookup: function (d) {
                        $gs(['lookupsDiv', 'lookupIdDiv']);
                        $g('lookupId').val(d.lookupId || '');
                        $g('lookupWidth').val(d.lookupWidth = d.lookupWidth || 640);
                        $g('lookupHeight').val(d.lookupHeight = d.lookupHeight || 480);
                        $g('lookupMulti').prop('checked', d.lookupMulti = !!d.lookupMulti);
                        $g('lookupType').val(d.lookupType || 'none');
                        $g('lookupParam').val(d.lookupParam || '');
                        $g('lookupFilter').val(d.lookupFilter || '');

                        lookupIdOn({value: d.lookupId});
                        lookupMutiOn({elem: {checked: d.lookupMulti}});
                    },
                    field: function (val) {
                        $gs(['fieldsDiv']);
                        let o = $g('field');

                        loadFields(args.bindType === 'entity', args.bindType === 'table' ? args.mainTable : args.mainEntity, function (r) {
                            fillOpts(o, '请选择', r.data, val, (it) => [
                                it[0], it[0] + '　- ' + it[1]
                            ]);
                            $g('field').append('<option value="@">其它自定义</option>');
                            if (!val || o.find('option[value=' + val + ']').length) {
                                $gs([], ['tFieldDiv']);
                            } else {
                                o.val('@');
                                $gs(['tFieldDiv']);
                                $g('tField').val(val);
                            }
                            layui.form.render(null, rtForm.attr('id'));
                        });
                    },
                    manyType: function (val) {
                        $gs(['manyTypeDiv']);
                        let o = $g('manyType');
                        try {
                            o.val(val || 'none');
                        } catch (e) {
                            o.val('none');
                        }
                    },
                    treeId: function (val, d) {
                        $gs(['treeIdDiv', 'treeOnlyLeafDiv', 'treeDisplayDiv']);
                        let o = $g('treeId');
                        try {
                            o.val(val || '');
                        } catch (e) {
                            o.val('');
                        }
                        o = $g('treeDisplay');
                        try {
                            o.val(d.treeDisplay || 'separator');
                        } catch (e) {
                            o.val('');
                        }
                        d.treeDisplay = o.val();


                        $g('treeOnlyLeaf').prop('checked', !!d.treeOnlyLeaf);
                    },
                    label: function (val) {
                        $gs(['labelDiv']);
                        $g('label').val(val);
                    },
                    type: function (val) {
                        $gs(['typeDiv']);
                        let o = $g('type');
                        try {
                            o.val(val);
                        } catch (e) {
                            o.val('input');
                        }
                    },
                    format: function (val) {
                        $gs(['formatDiv']);
                        let o = $g('format');
                        try {
                            o.val(val = val || 'text');
                        } catch (e) {
                            o.val('text');
                        }
                        if ('joinTable' === val || 'joinEntity' === val) {
                            if ('joinTable' === val) {
                                $gs(['outjoinDiv', 'joinTableDiv'], ['joinEntityDiv']);
                            } else {
                                $gs(['outjoinDiv', 'joinEntityDiv'], ['joinTableDiv']);
                            }
                        } else {
                            $gs([], ['outjoinDiv']);
                        }
                        if ('pwd' === val) {
                            $gs(['pwdTypeDiv']);
                        } else {
                            $gs([], ['pwdTypeDiv']);
                        }
                    },
                    fileMultipart: function (val) {
                        $gs(['fileMultipartDiv']);
                        let o = $g('fileMultipart');
                        if (val === undefined || val === null) val = 'one';
                        o.val(val);
                    },
                    fileDel: function (val) {
                        $gs(['fileDelDiv']);
                        $g('fileDel').prop('checked', !!val);
                    },
                    fileType: function (val) {
                        $gs(['fileTypeDiv']);
                        let o = $g('fileType');
                        if (val === undefined || val === null) val = 'any';
                        o.val(val);
                    },
                    fileExtensions: function (val) {
                        $gs(['fileExtensionsDiv']);
                        let o = $g('fileExtensions');
                        if (val === undefined || val === null) val = '';
                        o.val(val);
                    },
                    room: function (val) {
                        $gs(['roomDiv']);
                        let o = $g('room');
                        if (val === undefined || val === null) val = 'none';
                        o.val(val);
                    },
                    roomTo: function (w, h) {
                        $gs(['roomToDiv']);
                        $g('roomW').val(w || 0);
                        $g('roomH').val(h || 0);
                    },
                    fileSize: function (val) {
                        $gs(['fileSizeDiv']);
                        let o = $g('fileSize');
                        if (val === undefined || val === null) val = '';
                        o.val(val);
                    },
                    renameType: function (val) {
                        $gs(['renameTypeDiv']);
                        let o = $g('renameType');
                        if (val === undefined || val === null) val = '0';
                        o.val(val);
                    },
                    fileName: function (val) {
                        let {t, d} = $selected();
                        if (d.renameType == '2') {
                            $gs(['fileNameDiv']);
                            let o = $g('fileName');
                            if (val === undefined || val === null) val = '';
                            o.val(val);
                        }else $gs([],['fileNameDiv']);
                    },
                    required: function (val) {
                        $gs(['requiredDiv']);
                        $g('required').prop('checked', !!val);
                    },
                    noStore: function (val) {
                        $gs(['noStoreDiv']);
                        $g('noStore').prop('checked', !!val);
                    },
                    readonly: function (val) {
                        $gs(['readonlyDiv']);
                        $g('readonly').val(val || 0);
                    },
                    maxlength: function (val) {
                        $gs(['maxlengthDiv']);
                        $g('maxlength').val(val === undefined || val == null ? '' : val);
                    },
                    height: function (val) {
                        $gs(['heightDiv']);
                        $g('height').val(val || 100);
                    },
                    minChk: function (val) {
                        $gs(['minChkDiv']);
                        $g('minChk').val(val || 0);
                    },
                    maxChk: function (val) {
                        $gs(['maxChkDiv']);
                        $g('maxChk').val(val || '');
                    },
                    placeholder: function (val) {
                        $gs(['placeholderDiv']);
                        $g('placeholder').val(val === undefined ? '' : val);
                    },
                    tips: function (val) {
                        $gs(['tipsDiv']);
                        $g('tips').val(val === undefined ? '' : val);
                    },
                    ont: function (val) {
                        $gs(['ontDiv']);
                        $g('ont').val(val || '开|关');
                    },
                    onv: function (val) {
                        $gs(['onvDiv']);
                        $g('onv').val(val || '1|0');
                    },
                    search: function (val) {
                        $gs(['searchDiv']);
                        $g('search').prop('checked', !!val);
                    },
                    opts: function (val, d) {
                        let isOneToMany = d.type === 'checkbox' && d.manyType === 'OneToMany',
                            isManyToMany = d.type === 'checkbox' && d.manyType === 'ManyToMany';
                        $gs(['optsDiv'], ['manyDiv']);
                        if (!isOneToMany && !isManyToMany) {
                            $('#labid' + args.uid).text('值字段');
                            $gs(['itemsDiv']);
                            $g('items').val(d.items === undefined ? '' : d.items);
                        } else {
                            $gs([], ['itemsDiv']);
                            if (d.optType !== 'table' && d.optType !== 'entity') d.optType = null;
                            $('#labid' + args.uid).text('外键字段');
                            if (isManyToMany) {
                                $gs(['manyDiv']);
                                let manyTable = $g('manyTable');
                                try {
                                    manyTable.val(d.manyTable || '');
                                } catch (e) {
                                    manyTable.val('');
                                }
                                manyTableOn({value: d.manyTable});
                            }
                        }
                        optTypeOn({value: $g('optType').val(d.optType || '').val()});
                    },
                    initial: function (val) {
                        $gs(['initialDiv']);
                        $g('initial').val(val === undefined ? '' : val);
                    },
                    pattern: function (val) {
                        $gs(['patternDiv']);
                        $g('pattern').val(val || '');
                    },
                    patternMsg: function (val) {
                        $gs(['patternMsgDiv']);
                        $g('patternMsg').val(val || '');
                    },
                    layout: function (val) {
                        let div = $g('layoutDiv');
                        if (val === null) {
                            div.hide();
                            nolay.show();
                            return;
                        }
                        div.show();
                        nolay.hide();
                        try {
                            $g('layout').val(val);
                            form.render('select', rtForm.get("id"));
                        } catch (e) {
                        }
                        if (val === 'free') $gs(['lay_widthDiv']);
                        else $gs([], ['lay_widthDiv']);
                    },
                    width: function (val) {
                        $g('lay_width').val(val || '');
                    },
                    existsChk: function (val, d) {
                        if (val) {
                            $gs(['existsChkDiv', 'existsMsgDiv', 'existsFilterDiv']);
                            $g('existsChk').prop('checked', true);
                            $g('existsMsg').val(d.existsMsg || '');
                            $g('existsFilter').val(d.existsFilter || '');
                        } else {
                            $gs(['existsChkDiv'], ['existsMsgDiv', 'existsFilterDiv']);
                            $g('existsChk').prop('checked', false);
                        }
                    },
                    conditionShow: function (val) {
                        $gs(['conditionShowDiv']);
                        $g('conditionShow').val(val || '');
                    }
                }
            };

        if (!body.data('inDrag_isBind')) {
            jdiyAdmin.inDesign = {
                dragging: false,
                dragThis: null,
                dragThat: null,
                dragTo: null,
                mouse: null,
                pos: 0, /*上右下左: 1234*/
                line: $('<div class="jdiy-drag-line"></div>').appendTo(body),
                follow: $('<div class="jdiy-drag-follow">拖拽鼠标可调整选中元素位置</div>').appendTo(body)
            };
            body.data('inDrag_isBind', true);
            body.mousemove(function (evt) {
                let drag = jdiyAdmin.inDesign;
                if (drag.dragging) {
                    drag.follow.css({
                        left: (evt.clientX + 30) + 'px',
                        top: (evt.clientY + 20) + 'px'
                    }).show();
                }
            }).mouseup(function () {
                $('body').removeClass('drag-move');
                $('.jdiy-drag-highlight').removeClass('jdiy-drag-highlight');
                let drag = jdiyAdmin.inDesign || false;
                if (!drag.dragging) return;

                if (drag.pos && drag.line.is(':visible')) {
                    let p, np, toJq;
                    if (drag.pos === 1 || drag.pos === 3) {//1:目标元素上方  3:置于目标元素下方
                        toJq = drag.dragTo.hasClass('layui-form-item') ? drag.dragTo : drag.dragTo.parent();
                        p = drag.dragThis.parent();
                        if (drag.pos === 1) np = $('<div class="layui-form-item"></div>').insertBefore(toJq);
                        else np = $('<div class="layui-form-item"></div>').insertAfter(toJq);
                        drag.dragThis = drag.dragThis.css({opacity: 1}).appendTo(np);
                        if (p.children().length < 1) p.remove();
                    } else if (drag.pos === 2 || drag.pos === 4) {//2:目标元素右方  4:目标元素左左方
                        p = drag.dragThis.parent();
                        if (drag.pos === 4) drag.dragThis.insertBefore(drag.dragTo);
                        else drag.dragThis.insertAfter(drag.dragTo);
                        if (p.children().length < 1) p.remove();
                    }
                }

                drag.follow.hide();
                drag.line.hide();
                drag.dragTo = null;
                drag.dragThis.css({opacity: 1});
                drag.dragging = false;
            });
        }
        canvas.mouseup(function () {
            setTimeout(function () {
                showTool();
            }, 200);
        }).mousedown(function (e) {
            let dragThis = $(e.target),
                selected = canvas.find('.jdiy-selected'),
                isTool = dragThis.hasClass('jdiy-design-tool') || dragThis.parents('.jdiy-design-tool').length > 0;
            if (isTool) return;
            if (!dragThis.hasClass('jdiy-in-obj')) dragThis = dragThis.parents('.jdiy-in-obj');
            if (dragThis.is(selected)) {
                body.addClass('drag-move');
                startDrag(e, dragThis);
                showTool(true);
            } else if (dragThis.length === 1) {
                doSelect(dragThis);
            }
        }).mousemove(function (e) {
            let drag = jdiyAdmin.inDesign;
            if (!drag.dragging) return;
            let that = drag.dragThat = $(e.target).parents('.jdiy-in-obj');
            if (drag.dragThat.length < 1) return;
            if (drag.dragThat.is(drag.dragThis)) {
                drag.line.hide();
                drag.dragTo = null;
                drag.dragThis.css({opacity: 1});
                drag.follow.html('拖拽鼠标可调整当前元素位置').css('color', 'red').show();
                canvas.find('.jdiy-drag-highlight').removeClass('jdiy-drag-highlight');
            } else {
                let ofX = e.clientX - drag.mouse.x, ofXa = Math.abs(ofX),
                    ofY = e.clientY - drag.mouse.y, ofYa = Math.abs(ofY),
                    lazy = 5,//移过指定像素，才判断显示目标位置
                    toob,
                    css1;
                if (ofYa < ofXa) {
                    toob = that;
                    css1 = {width: '3px', height: that.outerHeight() + 'px', top: (that.offset().top) + 'px'};
                    if (ofX > lazy) {//右
                        if (that.hasClass('noInline') || drag.dragThis.hasClass('noInline')) {/*部分控件必须独行显示*/
                            toob = that.hasClass('layui-inline') ? that.parent() : that;
                            drag.pos = 3;
                            css1 = {
                                height: '3px', width: toob.outerWidth() + 'px', left: (toob.offset().left) + 'px',
                                top: (toob.offset().top + 6 + toob.outerHeight()) + 'px'
                            };
                        } else {
                            drag.pos = 2;
                            css1.left = (toob.offset().left + 6 + toob.outerWidth()) + 'px';
                        }
                    } else if (ofX < -lazy) {//左
                        if (that.hasClass('noInline') || drag.dragThis.hasClass('noInline')) {/*部分控件必须独行显示*/
                            toob = that.hasClass('layui-inline') ? that.parent() : that;
                            drag.pos = 1;
                            css1 = {
                                height: '3px', width: toob.outerWidth() + 'px', left: (toob.offset().left) + 'px',
                                top: (toob.offset().top - 6) + 'px'
                            };
                        } else {
                            drag.pos = 4;
                            css1.left = (toob.offset().left - 6) + 'px';
                        }
                    } else {
                        css1 = null;
                    }
                } else {
                    toob = that.hasClass('layui-inline') ? that.parent() : that;
                    css1 = {height: '3px', width: toob.outerWidth() + 'px', left: (toob.offset().left) + 'px'};
                    if (ofY > lazy) {//下
                        drag.pos = 3;
                        css1.top = (toob.offset().top + 6 + toob.outerHeight()) + 'px';
                    } else if (ofY < -lazy) {//上
                        drag.pos = 1;
                        css1.top = (toob.offset().top - 6) + 'px';
                    } else {
                        css1 = null;
                    }
                }
                if (css1 != null) {
                    canvas.find('.jdiy-drag-highlight').removeClass('jdiy-drag-highlight');
                    toob.addClass('jdiy-drag-highlight');
                    drag.mouse = {x: e.clientX, y: e.clientY};
                    drag.dragTo = that;
                    drag.line.show().css(css1);
                    drag.dragThis.css({opacity: 0.1});
                    drag.follow.show().html('放开鼠标可将元素移至红线处').css('color', 'green');
                }
            }
        });

        selectOn('type', function (o) {
            let {t, d} = $selected(), nt;
            d.type = o.value;
            let h = builder.wrap(d);
            if (d.type === 'ueditor' || d.type === 'file') {//需要独行
                let p = t.parent(),
                    np = $('<div class="layui-form-item"></div>').insertAfter(p);
                nt = $(h).appendTo(np).addClass('jdiy-selected');
                t.remove();
                if (p.children().length < 1) p.remove();
            } else {
                nt = $(h).insertAfter(t).addClass('jdiy-selected');
                t.remove();
            }
            layui.form.render(null, canvas.attr('id'));

            builder.showProp(d.type, d);
            doSelect(nt);
        });
        selectOn('format', function (o) {
            let {t, d} = $selected();
            if ((d.format = o.value) === 'joinTable' || d.format === 'joinEntity') {
                if (d.format === 'joinTable') {
                    $gs(['outjoinDiv', 'joinTableDiv'], ['joinEntityDiv']);
                    joinTableOn($g('joinTable')[0]);
                } else {
                    $gs(['outjoinDiv', 'joinEntityDiv'], ['joinTableDiv']);
                    joinTableOn($g('joinEntity')[0]);
                }
            } else {
                $gs([], ['outjoinDiv']);
            }


            if ((d.format = o.value) === 'pwd') {
                $gs(['pwdTypeDiv']);
            } else {
                $gs([], ['pwdTypeDiv']);
            }
            t.find('input').val(inputval(d));
        });

        selectOn('field', function (o) {
            let {t, d} = $selected();
            if (o.value === '@') {
                $gs(['tFieldDiv']);
                $g('tField').val(d.field = '');
            } else {
                $gs([], ['tFieldDiv']);
                d.field = o.value;
            }
            $(builder.wrap(d)).insertAfter(t).addClass('jdiy-selected');
            t.remove();
            layui.form.render(null, canvas.attr('id'));
        });

        selectOn('lookupId', lookupIdOn);
        $g('lookupParam').keyup(function () {
            let {d} = $selected();
            d.lookupParam = this.value;
        });
        $g('lookupFilter').keyup(function () {
            let {d} = $selected();
            d.lookupFilter = this.value;
        });
        $g('lookupWidth').keyup(function () {
            let {d} = $selected();
            let p = parseInt(this.value);
            d.lookupWidth = this.value = isNaN(p) || p < 0 ? 640 : p;
        });
        $g('lookupHeight').keyup(function () {
            let {d} = $selected();
            let p = parseInt(this.value);
            d.lookupHeight = this.value = isNaN(p) || p < 0 ? 640 : p;
        });
        selectOn('lookupField', function (o) {
            let {d} = $selected();
            d.lookupField = o.value;
        });
        switchOn('lookupMulti', lookupMutiOn);
        selectOn('lookupType', lookupTypeOn);
        selectOn('lookupJoinField', function (o) {
            let {d} = $selected();
            d.lookupJoinField = o.value;
        });
        selectOn('lookupJoinTable', lookupJoinTableOn);
        selectOn('lookupJoinField0', function (o) {
            let {d} = $selected();
            d.lookupJoinField0 = o.value;
        });
        selectOn('lookupJoinField1', function (o) {
            let {d} = $selected();
            d.lookupJoinField1 = o.value;
        });

        selectOn('treeId', function (o) {
            let {d} = $selected();
            d.treeId = o.value;
        });
        switchOn('treeOnlyLeaf', function (o) {
            let {d} = $selected();
            d.treeOnlyLeaf = o.elem.checked;
        });
        selectOn('treeDisplay', function (o) {
            let {d} = $selected();
            d.treeDisplay = o.value;
        });
        selectOn('manyType', function (o) {
            let {d} = $selected();
            d.manyType = o.value;
            builder.showProp(d.type, d);
        });
        selectOn('manyField0', function (o) {
            let {d} = $selected();
            d.manyField0 = o.value;
        });
        selectOn('manyField1', function (o) {
            let {d} = $selected();
            d.manyField1 = o.value;
        });
        $g('tField').keyup(function () {
            let {t, d} = $selected();
            if (this.value !== '' && !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(this.value)) {
                let ov = $(this).data('oldval');
                this.value = ov === undefined || ov == null ? '' : ov;
            } else {
                $(this).data('oldval', this.value);
            }
            d.field = this.value;
            $(builder.wrap(d)).insertAfter(t).addClass('jdiy-selected');
            t.remove();
            layui.form.render(null, canvas.attr('id'));
        });

        $g('label').keyup(function () {
            let {t, d} = $selected();
            d.label = this.value;
            t.find('>label').html(this.value);
        });
        selectOn('fileMultipart', function (o) {
            let {d} = $selected();
            d.fileMultipart = o.value;
        });
        switchOn('fileDel', function (o) {
            let {d} = $selected();
            d.fileDel = o.elem.checked;
        });

        selectOn('fileType', function (o) {
            let {t, d} = $selected();
            d.fileType = o.value;
            doSelect(t);
        });

        $g('fileExtensions').keyup(function () {
            let {d} = $selected();
            d.fileExtensions = this.value;
        });

        selectOn('room', function (o) {
            let {t, d} = $selected();
            d.room = o.value;
            doSelect(t);
        });

        $g('roomW').keyup(function () {
            let {d} = $selected();
            let p = parseInt(this.value);
            if (isNaN(p) || p < 0) d.roomW = this.value = 0;
            else d.roomW = this.value = p;
        });

        $g('roomH').keyup(function () {
            let {d} = $selected();
            let p = parseInt(this.value);
            if (isNaN(p) || p < 0) d.roomH = this.value = 0;
            else d.roomH = this.value = p;
        });
        $g('fileSize').keyup(function () {
            let {d} = $selected();
            let p = parseInt(this.value);
            if (isNaN(p) || p < 0) d.fileSize = this.value = 0;
            else d.fileSize = this.value = p;
        });
        selectOn('renameType', function (o) {
            let {t, d} = $selected();
            if((d.renameType = o.value)=='2') {
                $gs(['fileNameDiv']);
            }else{
                $gs([],['fileNameDiv']);
            }
        });
        $g('fileName').keyup(function () {
            let {d} = $selected();
            d.fileName = this.value;
        });

        switchOn('required', function (o) {
            let {d} = $selected();
            d.required = o.elem.checked;
        });
        switchOn('noStore', function (o) {
            let {d} = $selected();
            d.noStore = o.elem.checked;
        });
        selectOn('readonly', function (o) {
            let {t, d} = $selected();
            d.readonly = o.value;
            let h = builder.wrap(d);
            $(h).insertAfter(t).addClass('jdiy-selected');
            t.remove();
            layui.form.render(null, canvas.attr('id'));
        });
        $g('minChk').keyup(function () {
            let {d} = $selected();
            this.value = d.minChk = this.value === '' ? '' : parseInt(this.value) || 0;
        });
        $g('maxChk').keyup(function () {
            let {d} = $selected();
            this.value = d.maxChk = this.value === '' ? '' : parseInt(this.value) || 999;
        });
        $g('maxlength').keyup(function () {
            let {d} = $selected(),
                v = parseInt(this.value) || 0;
            if (v !== 0) this.value = v;
            d.maxlength = v;
        });
        $g('height').keyup(function () {
            let {t, d} = $selected(),
                v = parseInt(this.value) || 100;
            if (v < 60) v = 60;
            else if (v > 600) v = 600;
            d.height = v;
            t.find('>label').css({height: (v - 18) + 'px'});
            t.find('textarea').css({height: v + 'px'});
            showTool();
        });
        $g('placeholder').keyup(function () {
            let {t, d} = $selected();
            t.find('input, textarea').attr('placeholder', d.placeholder = this.value);
        });
        $g('tips').keyup(function () {
            let {t, d} = $selected();
            t.find('#'+d.id+"__tips").html(d.tips=this.value);
        });
        $g('ont').focus(function () {
            $(this).data('for-mit', canvas.find('.jdiy-selected').attr('id'));
        }).change(function () {
            let id = $(this).data('for-mit'),
                formid = id,
                t = $('#' + id),
                data = eData[formid],
                v = this.value;
            if (v !== '' && !/^.+?\|.+?$/.test(v)) {
                layui.layer.msg('开关文字需为 A|B 的格式，如： 打开|关闭　是|否　ON|OFF　启用|停用 等等.您输入的不正确已被系统还原成默认值');
                this.value = data.ont = v = '开|关';
            } else {
                data.ont = v;
            }
            t.find('input').attr('lay-text', v);
            let td = t.find('em'), sa = v.split('|');
            if (td.parent().hasClass('layui-form-onswitch')) td.html(sa[0]);
            else td.html(sa[1]);
        });
        $g('onv').focus(function () {
            $(this).data('for-mit', canvas.find('.jdiy-selected').attr('id'));
        }).change(function () {
            let id = $(this).data('for-mit'),
                formid = id,
                data = eData[formid],
                v = this.value;
            if (v !== '' && !/^.+?\|.+?$/.test(v)) {
                layui.layer.msg('开关值需为 A|B 的格式，如： 1|0　true|false　等等.您输入的不正确已被系统还原成默认值');
                this.value = data.onv = '1|0';
            } else {
                data.onv = v;
            }
        });
        switchOn('search', function (o) {
            let {t, d} = $selected();
            d.search = !!o.elem.checked;
            let h = builder.wrap(d);
            $(h).insertAfter(t).addClass('jdiy-selected');
            t.remove();
            layui.form.render(null, canvas.attr('id'));
        });
        switchOn('cascade', function (o) {
            let {t, d} = $selected();
            d.cascade = !!o.elem.checked;
        });

        $g('items').keyup(function () {
            let {t, d} = $selected();
            d.items = this.value;
            $(builder.wrap(d)).insertAfter(t).addClass('jdiy-selected');
            t.remove();
            layui.form.render(null, canvas.attr('id'));
        });

        selectOn('optType', optTypeOn);
        selectOn('optDict', function (o) {
            let {d} = $selected();
            d.optDict = o.value;
        });
        selectOn('optEntity', function (o) {
            let {d} = $selected();
            optTableOn({value: d.optEntity = o.value});

        });
        selectOn('optTable', function (o) {
            let {d} = $selected();
            optTableOn({value: d.optTable = o.value});
        });
        selectOn('optTxtField', function (o) {
            let {d} = $selected();
            d.optTxtField = o.value;
        });
        selectOn('optValField', function (o) {
            let {d} = $selected();
            d.optValField = o.value;
        });
        $g('optWhere').keyup(function () {
            let {d} = $selected();
            d.optWhere = this.value;
        });
        $g('optSort').keyup(function () {
            let {d} = $selected();
            d.optSort = this.value;
        });

        $g('optQry').keyup(function () {
            let {d} = $selected();
            d.optQry = this.value;
        });


        $g('optQry').keyup(function () {
            let {d} = $selected();
            d.optQry = this.value;
        });
        $g('initial').keyup(function () {
            let {d, t} = $selected();
            d.initial = this.value;
            if (d.type === 'colorbox' && d.initial) t.find('.layui-colorpicker-trigger-span').css('background-color', d.initial);
        });
        $g('conditionShow').keyup(function () {
            let {d} = $selected();
            d.conditionShow = this.value;
        });

        $g('headTips').keyup(function () {
            if (this.value !== '') {
                $g('headTipsBlock').html(this.value).show();
            } else {
                $g('headTipsBlock').html('').hide();
            }
            sData.headTips = $g('headTipsBlock').html();
        });
        $g('footTips').keyup(function () {
            if (this.value !== '') {
                $g('footTipsBlock').html(this.value).show();
            } else {
                $g('footTipsBlock').html('').hide();
            }
            sData.footTips = $g('footTipsBlock').html();
        });
        $('.pageTips').click(function () {
            canvas.find('.jdiy-selected').removeClass('jdiy-selected');
            layui.element.tabChange('rtTab_' + args.uid, 'rtTab2_' + args.uid);
        });

        $g('pattern').focus(function () {
            $(this).data('for-mit', canvas.find('.jdiy-selected').attr('id'));
        }).change(function () {
            eData[$(this).data('for-mit')].pattern = this.value;
        });
        $g('patternMsg').focus(function () {
            $(this).data('for-mit', canvas.find('.jdiy-selected').attr('id'));
        }).change(function () {
            eData[$(this).data('for-mit')].patternMsg = this.value;
        });
        switchOn('existsChk', function (o) {
            let {t, d} = $selected();
            if (d.existsChk = !!o.elem.checked) {
                $gs(['existsMsgDiv', 'existsFilterDiv']);
                $g('existsMsg').val(d.existsMsg);
                $g('existsFilter').val(d.existsFilter);
            } else {
                $gs([], ['existsMsgDiv', 'existsFilterDiv']);
            }
            $(builder.wrap(d)).insertAfter(t).addClass('jdiy-selected');
            t.remove();
            layui.form.render(null, canvas.attr('id'));
        });
        $g('existsMsg').keyup(function () {
            let {d} = $selected();
            d.existsMsg = this.value;
        });
        $g('existsFilter').keyup(function () {
            let {d} = $selected();
            d.existsFilter = this.value;
        });

        $g('inDesignReset').click(function () {
            layui.layer.confirm('此操作将撤销您对本页面所做的所有更改，确定要这样做吗？', function (index) {
                layui.layer.close(index);
                reset(null, canvas.find('.jdiy-selected').attr('id'));
                layui.layer.msg('已撤销还原!');
            });
        });
        selectOn('layout', function (o) {
            let {t, d} = $selected();
            if (d.type !== 'ueditor') {
                d.layout = o.value;
                $(builder.wrap(d)).insertAfter(t).addClass('jdiy-selected');
                t.remove();
                layui.form.render(null, canvas.attr('id'));
            }

            if (o.value === 'free') {
                $gs(['lay_widthDiv']);
                $g('lay_width').val(d.width || '');
            } else {
                $gs([], ['lay_widthDiv']);
            }
        });

        $g('lay_width').keyup(function () {
            let {t, d} = $selected();
            d.width = parseInt(this.value) || 0;
            t.find('.inpDiv').css({width: d.width === 0 ? '' : d.width});
        });

        switchOn('ajaxSave', function (o) {
            if (sData.ajaxSave = !!o.elem.checked) {
                $gs(['ajaxUrlDiv'], ['pkTplDiv', 'pkPreDiv', 'pkLenDiv']);
            } else {
                $gs(['pkTplDiv', 'pkPreDiv', 'pkLenDiv'], ['ajaxUrlDiv']);
            }
        });
        $g('ajaxUrl').keyup(function () {
            sData.ajaxUrl = this.value;
        });

        selectOn('pkTpl', function (o) {
            let v = o.value;
            if(v==='dates')$gs(['pkLenDiv'],['pkPreDiv']);
            else if(v==='pres')$gs(['pkLenDiv','pkPreDiv']);
            else $gs([], ['pkLenDiv', 'pkPreDiv']);
        });

        let _eventScriptHelp = '// 此处文字仅供指导(编写javascript脚本时请先清空如下内容)\n\n' +
            '//     ★请自行确保您输入的js代码无误，否则目标界面在加载渲染时可能出现异常★\n\n' +
            '// 可以直接使用如下内置对象：\n' +
            '//  $          即jQuery对象\n' +
            '//  form     当前的表单对象\n\n' +
            '// 简单示例仅供参考(假设页面中有个名为age的文本框，当输入内容不是整数时边框变成红色):\n' +
            '//  $(form.age).change(function(){\n' +
            '//      if(parseInt(this.value)!=this.value){\n' +
            '//          $(this).css({border:"1px green solid"});\n' +
            '//      }else{\n' +
            '//          $(this).css({border:""});\n' +
            '//      }\n' +
            '//  });', _escssFn = function (v) {
            if (v) {
                $g('eventScript').html('<i class="layui-icon layui-icon-senior"></i>已配置事件脚本');
            } else {
                $g('eventScript').html('<i class="layui-icon layui-icon-senior"></i>未配置，点此设置');
            }
        };
        $g('eventScript').click(function () {
            layer.prompt({
                formType: 2,
                allowEmpty: true,
                value: sData.eventScript || _eventScriptHelp,
                title: '脚本内容：',
                maxlength: 10000,
                area: ['800px', '350px'] //自定义文本域宽高
            }, function (value, index) {
                _escssFn(sData.eventScript = value === _eventScriptHelp ? '' : value);
                layer.close(index);
            });
        });

        selectOn('joinTable', joinTableOn);
        selectOn('joinEntity', joinTableOn);
        selectOn('manyTable', manyTableOn);
        selectOn('joinField', function (o) {
            let {t, d} = $selected();
            d.joinField = o.value;
            t.find('input').val(inputval(d));
        });
        selectOn('pwdType', function (o) {
            let {t, d} = $selected();
            d.pwdType = o.value;
            t.find('input').val(inputval(d));
        });

        $g('inDesignSave').click(function () {
            save();
        });

        $(rtForm).find('.jdiy-form-help').click(function () {
            let ui = 'form', help = $(this).data('help'),
                helpMe = (h) => typeof h == 'object' ? layer.open(h) : layer.tips(h, '.jdev-prop-' + help + args.uid, {
                    tips: [4, '#FF5722'],
                    time: 10000
                });
            help && layui.jdhp && layui.jdhp[ui] && layui.jdhp[ui][help] &&
            helpMe(
                typeof layui.jdhp[ui][help] == 'function'
                    ? layui.jdhp[ui][help](args.uid)
                    : layui.jdhp[ui][help]
            );
        });
        reset();
    }

    exports('formDesign', {
        render: design_in_main
    });
});

